package com.sky.controller.user;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "菜品相关接口")
@RestController("userDishController")
@RequestMapping("/user/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation("根据id查询菜品信息")
    @GetMapping("/{id}")
    public Result<DishVO> findById(@PathVariable Long id) {
        DishVO dishVO = dishService.findById(id);
        return Result.success(dishVO);
    }

    @ApiOperation("根据分类id查菜品")
    @GetMapping("/list")
    public Result<List<DishVO>> list(Long categoryId) {
        //构造redis中的key
        String key = "dish_" + categoryId;
        //查询redis中是否存在菜品数据
        List<DishVO> list = (List<DishVO>) redisTemplate.opsForValue().get(key);
        //存在 直接返回 无需查询数据库
        if(list!=null&& !list.isEmpty()){
            return Result.success(list);
        }
        //不存在 查数据库 再写到redis中
        list = dishService.findBycategoryId(categoryId);
        redisTemplate.opsForValue().set(key,list);
        return Result.success(list);
    }
}
